/**
 * 养殖企业
 * @constructor
 */
function Breed() {
}

Breed.init = function () {
    getHarmlessId();        //无害化企业下拉选赋值
    getHarmlessId2();       //无害化企业下拉选赋值
    let vm = new Vue({
        el: "#customModule",
        data: {
            //实体
            enterpriseId: "",
            enterpriseName: "",
            userName: "",
            phone: "",
            detailedAddress: "",
            investment: "",
            area: "",
            idcard: "",
            identification: "",
            certificate: "",
            certificateCode: "",
            scope: "",
            remark: "",
            examine: 1,
            opinion: "",
            text_cityCode:'',
            text_cityCodeList:[],
            text_districtCode:'',
            text_districtCodeList:[],
            text_townCode:'',
            text_townCodeList:[],
            //搜索值
            enterpriseNameCondition: "",
            userNameCondition: "",
            examineCondition: 0,
            cityCondition: -1,
            districtCondition: -1,
            townCondition: -1,
            cityList:[], //城市集合
            districtList:[], //区县集合
            townList:[],   //乡镇集合
            text_starCity:"",
            //附加属性
            clickState: "",
            roleID: "",
            isAdd: "true",
            roleList: "",
            city: true,
            district: true,
            town: true
        },
        created() {
            this.roleID = $.cookie('RoleIds');
            self = this;
            window.changeState = self.changeState;
            window.edit = self.edit;
            window.toExamine = self.toExamine;
            window.resetPassword = self.resetPassword;
        },
        mounted() {
            this.initBootStrapSource();
            this.getAuth();
            this.initCity();
        },
        watch:{
            cityCondition:function (city_id) {
                this.initDistrict(city_id);
            },
            districtCondition:function (district_id) {
                this.initTown(district_id);
            },
            text_cityCode:function (city_id) {
                this.initDistrict1(city_id);
            },
            text_districtCode:function (district_id) {
                this.initTown1(district_id);
            }
        },
        methods: {
            initBootStrapSource() {
                $('#tableList').bootstrapTable({
                    url: '/breed/tableSearch',
                    method: 'post',
                    toolbar: "#toolbar",
                    sidePagination: 'server',
                    dataField: "data",
                    striped: true,
                    pagination: true,
                    pageNumber: 1,
                    pageSize: 10,
                    pageList: [10, 25, 50, 100],
                    sortable: true,
                    sortName: 'createDateTime',
                    sortOrder: "desc",
                    search: false,
                    showRefresh: true,
                    showColumns: true,
                    showExport: true,
                    showToggle: true,
                    queryParamsType: 'undefined',
                    queryParams: function queryParams(params) {
                        return {
                            pageSize: params.pageSize,      //页面大小
                            pageIndex: params.pageNumber,   //页码
                            sort: params.sortName,      //排序列名
                            sortOrder: params.sortOrder, //排位命令（desc，asc）
                            enterpriseName: $("#enterpriseNameCondition").val(),
                            userName: $("#userNameCondition").val(),
                            examine: $("#examineCondition").val(),
                            cityCode: $("#cityCondition").val(),
                            districtCode: $("#districtCondition").val(),
                            townCode: $("#townCondition").val(),
                        };
                    },
                    onLoadSuccess: function (data) {
                        //Help.alertSuccMessage("数据加载完毕");
                    },
                    onLoadError: function (status) {
                        // Help.alertErrorMessage("数据加载出错");
                    },
                    detailView: true, //是否显示详情折叠
                    detailFormatter: function (index, row, element) {
                        console.log("rows", row);
                        let examine;
                        if (row.examine === 0) {
                            examine = "未审核";
                        } else if (row.examine === 1) {
                            examine = "审核通过";
                        } else if (row.examine === 2) {
                            examine = "审核未通过";
                        }
                        //    详情折叠 内容 其他类型的动物
                        if (row.animalTypes === 0) {
                            let str =
                                "<table frame=void>" +
                                "<tr>" +
                                "<td>投资规模（元）：" + row.investment + "</td>" +
                                "<td>占地面积：" + row.area + "</td>" +
                                "<td>地理坐标：" + ((row.longitude == null || row.latitude == null) ? '' : (row.longitude+ "," + row.latitude)) + "</td>" +
                                "<td>统一信用代码/身份证号：" + row.idCard + "</td>" +
                                "</tr>" +
                                "<tr>" +
                                "<td>畜禽标识代码：" + row.identification + "</td>" +
                                "<td>动物防疫条件合格证号：" + row.certificate + "</td>" +
                                "<td>动物防疫条件合格证编码：" + row.certificateCode + "</td>" +
                                "<td>动物防疫条件合格证经营范围：" + row.scope + "</td>" +
                                "</tr>" +
                                "<tr>" +
                                "<td>存栏数：" + row.livestock + "</td>" +
                                "<td>登录帐号：" + row.loginID + "</td>" +
                                "<td>审核状态：" + examine + "</td>" +
                                "<td>审核意见：" + row.opinion + "</td>" +
                                "</tr>" +
                                "<tr>" +
                                "<td>审核人：" + (row.examineName == null ? '' : row.examineName) + "</td>" +
                                "<td>审核时间：" + (row.examineTime == null ? '' : row.examineTime) + "</td>" +
                                "</tr>" +
                                "</table>"

                            return str;
                        } else if (row.animalTypes === 1) {
                            let str =
                                "<table style='border: 1px red solid'>" +
                                "<tr>" +
                                "<td>投资规模（元）：" + row.investment + "</td>" +
                                "<td>占地面积：" + row.area + "</td>" +
                                "<td>地理坐标：" + ((row.longitude == null || row.latitude == null) ? '' : (row.longitude+ "," + row.latitude)) + "</td>" +
                                "<td>统一信用代码/身份证号：" + row.idCard + "</td>" +
                                "</tr>" +
                                "<tr>" +
                                "<td>畜禽标识代码：" + row.identification + "</td>" +
                                "<td>动物防疫条件合格证号：" + row.certificate + "</td>" +
                                "<td>动物防疫条件合格证编码：" + row.certificateCode + "</td>" +
                                "<td>动物防疫条件合格证经营范围：" + row.scope + "</td>" +
                                "</tr>" +
                                "<tr>" +
                                "<td>种公畜数：" + row.species + "</td>" +
                                "<td>后备母畜数：" + row.reserve + "</td>" +
                                "<td>能繁母畜数：" + row.menstruation + "</td>" +
                                "<td>哺乳牲畜数：" + row.lactation + "</td>" +
                                "</tr>" +
                                "<tr>" +
                                "<td>保育牲畜数：" + row.conservation + "</td>" +
                                "<td>育成牲畜数：" + row.commodity + "</td>" +
                                "<td>登录帐号：" + row.loginID + "</td>" +
                                "<td>审核状态：" + examine + "</td>" +
                                "</tr>" +
                                "<tr>" +
                                "<td>审核意见：" + row.opinion + "</td>" +
                                "<td>审核人：" + (row.examineName == null ? '' : row.examineName) + "</td>" +
                                "<td>审核时间：" + (row.examineTime == null ? '' : row.examineTime) + "</td>" +
                                "</tr>" +
                                "</table>"

                            return str;
                        }

                    },
                    columns: [
                        {
                            title: '序号',//标题  可不加
                            align: "center",
                            width: 40,
                            sortable: true,
                            formatter: function (value, row, index) {
                                var pageSize = $('#tableList').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                                var pageNumber = $('#tableList').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                                return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                            }
                        },
                        {field: 'enterpriseName', title: '企业名称', align: 'center'},
                        {field: 'userName', title: '法人姓名', align: 'center'},
                        {field: 'phone', title: '联系电话', align: 'center'},
                        {field: 'animal', title: '饲养动物种类', align: 'center'},
                        {field: 'fullAddress', title: '地址', align: 'center'},
                        {field: 'createTime', title: '注册时间', align: 'center'},
                        {
                            field: 'examine', title: '审核状态', align: 'center',
                            formatter: function (value) {
                                let optionHtml = "";
                                if (value === 0) {
                                    optionHtml = "<span class=\"label label-danger custom\" style=\"cursor:pointer\">待审核</span>";
                                } else if (value === 1) {
                                    optionHtml = "<span class=\"label label-info\" style=\"cursor:pointer\">审核已通过</span>";
                                } else if (value === 2) {
                                    optionHtml = "<span class=\"label label-warning\" style=\"cursor:pointer\">审核未通过</span>";
                                }
                                return optionHtml;
                            }
                        },
                        {
                            field: 'activity', title: '状态', align: 'center',
                            formatter: function (value) {
                                let optionHtml = "";
                                if (value === 0) {
                                    optionHtml = "<span class=\"label label-danger custom\" style=\"cursor:pointer\">禁用</span>";
                                } else if (value === 1) {
                                    optionHtml = "<span class=\"label label-info\" style=\"cursor:pointer\">启用</span>";
                                }
                                return optionHtml;
                            }
                        },
                        {field: 'remark', title: '备注', align: 'center'},
                        {
                            title: '操作', align: 'center',
                            formatter: function (value, row, index) {
                                console.log("row", row)
                                let optionHtml = "<a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='edit(" + JSON.stringify(row) + ")'  title=\"修改\" ><i class=\"fa fa-edit\"></i>修改</a> ";

                                if (row.examine === 0) { //未审核
                                    optionHtml += " <a class=\"btn btn-danger btn-xs\" href=\"javascript:void(0)\"  onclick='toExamine(" + JSON.stringify(row) + ")' title=\"审核\"><i class=\"fa\"></i>审核</a>";
                                } else if (row.examine === 1) { //审核通过
                                    if (row.activity === 0) {
                                        optionHtml += "<span class=\"label label-info\" style=\"cursor:pointer\" onclick='changeState(" + JSON.stringify(row) + ")' title=\"启用\">启用</span>";
                                    } else if (row.activity === 1) {
                                        optionHtml += "<span class=\"label label-danger custom\" style=\"cursor:pointer\" onclick='changeState(" + JSON.stringify(row) + ")'  title=\"禁用\" >禁用</span> ";
                                    }
                                    optionHtml += "<a class=\"btn btn-warning btn-xs\" href=\"javascript:void(0)\"  onclick='resetPassword(" + JSON.stringify(row) + ")' title=\"重置密码\"><i class=\"fa\"></i>重置密码</a>";
                                    optionHtml += " <a class=\"btn btn-info btn-xs\" href=\"/breed/details?eid=" + row.enterpriseId + "\"><i class=\"fa\"></i>查看详情</a>";
                                } else {
                                    return null;
                                }
                                return optionHtml;
                            }
                        }
                    ]
                });

            },
            /**
             * 查询
             */
            search() {
                vm.refresh();
            },
            /**
             * 初始化地市
             */
            initCity(){
                let url = "/city/getAllCity"
                axios.get(url).then(data=>{
                    this.cityList = data.data;
                })
            },
            /**
             * 初始化区县
             */
            initDistrict(city_id){
                let url = "/district/getDistrictByCity?city_id="+city_id;
                axios.get(url).then(data=>{
                    this.districtList = data.data;
                })
            },
            /**
             * 初始化乡镇
             */
            initTown(district_id){
                let url = "/town/getTownByDistrict?district_id="+district_id;
                axios.get(url).then(data=>{
                    this.townList = data.data;
                })
            },


            /**
             * 初始化地市
             */
            initCity1(){
                let url = "/city/getAllCity"
                axios.get(url).then(data=>{
                    this.text_cityCodeList = data.data;
                })
            },
            /**
             * 初始化区县
             */
            initDistrict1(city_id){
                let url = "/district/getDistrictByCity?city_id="+city_id;
                axios.get(url).then(data=>{
                    this.text_districtCodeList = data.data;
                })
            },
            /**
             * 初始化乡镇
             */
            initTown1(district_id){
                let url = "/town/getTownByDistrict?district_id="+district_id;
                axios.get(url).then(data=>{
                    this.text_townCodeList = data.data;
                })
            },

            /**
             * 权限控制
             */
            getAuth() {
                let url = "/UserManage/getAuth";
                axios.post(url).then(data => {
                    if (data.data.code === "200") {
                        // cityCondition: -1,
                        //     districtCondition: -1,
                        //     townCondition: -1,
                        //判断用户权限
                        console.log('data.data.data', data.data.data);
                        if (data.data.data.authType == 1) { // 地市权限
                            // city: true,
                            // district: true,
                            // town: true
                            this.cityCondition = data.data.data.authCity;
                            this.district = false;
                            this.town = false;
                        }else if (data.data.data.authType == 2){ //区县权限
                            this.cityCondition = data.data.data.authCity;
                            this.districtCondition = data.data.data.authDistrict;
                            this.town = false;
                        }else if (data.data.data.authType == 3){ //乡镇权限
                            this.cityCondition = data.data.data.authCity;
                            this.districtCondition = data.data.data.authDistrict;
                            this.townCondition = data.data.data.authTown;
                        }
                    }
                });
            },
            /**
             * 重置
             */
            reset() {
                vm.enterpriseNameCondition = "";
                $("#enterpriseNameCondition").val("");
                vm.userNameCondition = "";
                $("#userNameCondition").val("");
                vm.examineCondition = "0";
                $("#examineCondition").val("0");
                vm.refresh();
            },
            /**
             * 编辑
             * @param data
             */
            edit(data) {
                if(data.examine==1){
                    document.getElementById("A").style.display = "block";
                    document.getElementById("B").style.display = "block";
                }else{
                    document.getElementById("A").style.display = "none";
                    document.getElementById("B").style.display = "none";
                }
                console.log("data222",data);
                vm.enterpriseId = data.enterpriseId;
                vm.enterpriseName = data.enterpriseName;
                vm.userName = data.userName;
                vm.phone = data.phone;
                vm.detailedAddress = data.fullAddress;
                vm.investment = data.investment;
                vm.area = data.area;
                vm.idcard = data.idCard;
                vm.identification = data.identification;
                vm.certificate = data.certificate;
                vm.certificateCode = data.certificateCode;
                vm.scope = data.scope;
                vm.remark = data.remark;
                vm.clickState = "edit";
                this.initCity1();
                this.text_cityCode = data.cityCode;
                this.initDistrict1(data.cityCode);
                this.text_districtCode = data.districtCode;
                this.initTown1(data.districtCode);
                this.text_townCode = data.townCode;

                // loadCities(data.cityCode,data.districtCode,data.townCode);
                $('#text_address').val(data.address);
                console.log("无害化企业id",data.harmlessId)
                $('#harmlessId2').val(data.harmlessId);
                $('#myModalAdd').modal('show');
            },
            /**
             * 审核
             * @param data
             */
            toExamine(data) {
                vm.enterpriseId = data.enterpriseId;
                vm.enterpriseName = data.enterpriseName;
                vm.userName = data.userName;
                vm.phone = data.phone;
                vm.detailedAddress = data.fullAddress;
                vm.investment = data.investment;
                vm.area = data.area;
                vm.idcard = data.idCard;
                vm.identification = data.identification;
                vm.certificate = data.certificate;
                vm.certificateCode = data.certificateCode;
                vm.scope = data.scope;
                vm.remark = data.remark;
                $('#myModalAdd1').modal('show');
            },
            /**
             * 重置密码
             * @param data
             */
            resetPassword(data) {
                swal({
                    title: "确认是否重置密码",
                    text: "是否确认要为该企业重置密码？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "重置",
                    cancelButtonText: "取消",
                    closeOnConfirm: false
                }, function () {
                    let url = "/breed/resetPassword";
                    let pm = {
                        enterpriseId: data.enterpriseId
                    };
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            swal("操作成功!", "请继续操作", "success");
                            vm.refresh();
                        } else {
                            swal("操作失败!", "请重试", "error");
                        }
                    });
                });
            },
            /**
             * 切换状态显示
             * @param data
             */
            changeState(data) {
                let activity = "";
                let activityNum = "";
                if (data.activity === 0) {
                    activity = "启用";
                    activityNum = 1;
                } else if (data.activity === 1) {
                    activity = "禁用";
                    activityNum = 0;
                }
                swal({
                    title: "确认是否" + activity,
                    text: "是否确认要" + activity + "该企业？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: activity,
                    cancelButtonText: "取消",
                    closeOnConfirm: false
                }, function () {
                    let url = "/breed/edit";
                    let pm = {
                        enterpriseId: data.enterpriseId,
                        activity: activityNum
                    };
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            swal("操作成功!", "请继续操作", "success");
                            vm.refresh();
                        } else {
                            swal("操作失败!", "请重试", "error");
                        }
                    });
                });
            },
            /**
             * 新增
             */
            addRecord() {
                vm.immuneID = "";
                vm.uID = "";
                vm.immuneTime = "";
                vm.number = "";
                vm.vaccineName = "";
                vm.manufacturers = "";
                vm.batchNumber = "";
                vm.validity = "";
                vm.createTime = "";
                vm.dose = "";
                vm.methods = "";
                vm.remark = "";
                vm.clickState = "add";
                $('#myModalAdd').modal('show');
            },
            /**
             * 保存
             */
            saveRecord() {
                if (!validateForm()) return false;
                let pm = {
                    enterpriseId: vm.enterpriseId,
                    enterpriseName: vm.enterpriseName,
                    phone: vm.phone,
                    idCard: vm.idcard,
                    identification: vm.identification,
                    certificate: vm.certificate,
                    certificateCode: vm.certificateCode,
                    scope: vm.scope,
                    remark: vm.remark,
                    cityCode:$("#text_cityCode").val(),
                    districtCode:$("#text_districtCode").val(),
                    townCode:$("#text_townCode").val(),
                    address:$("#text_address").val(),
                    fullAddress:$("#text_cityCode").find("option:selected").text()+$("#text_districtCode").find("option:selected").text()+$("#text_townCode").find("option:selected").text()+$("#text_address").val(),
                    harmlessId:$("#harmlessId2").val(),
                }
                console.log("pm", pm)
                if (vm.clickState === "edit") {
                    let url = "/breed/edit";
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            $('#myModalAdd').modal('hide')
                            swal("修改成功!", "请继续操作", "success");
                            this.refresh();
                        }
                    }).catch(e => {
                        console.log(e);
                        swal("修改失败!", "请重试", "error");
                    });
                } else if (vm.clickState === "add") {
                    let url = "/immune/add";
                    axios.post(url, pm).then(data => {
                        $('#tableList').bootstrapTable(('refresh'));
                        if (data.data.code === "200") {
                            $('#myModalAdd').modal('hide')
                            swal("添加成功!", "请继续操作", "success");
                            this.refresh();
                        }
                    }).catch(e => {
                        console.log(e);
                        swal("添加失败!", "请重试", "error");
                    });
                }
            },
            saveRecord1() {
                let pm = {
                    enterpriseName: vm.enterpriseName,
                    phone: vm.phone,
                    enterpriseId: vm.enterpriseId,
                    examine: vm.examine,
                    opinion: vm.opinion,
                    harmlessId:$("#harmlessId").val(),
                }
                let url = "/breed/toExamine";
                axios.post(url, pm).then(data => {
                    if (data.data.code === "200") {
                        $('#myModalAdd1').modal('hide')
                        swal("操作成功!", "请继续操作", "success");
                        this.refresh();
                    }
                }).catch(e => {
                    console.log(e);
                    swal("操作失败!", "请重试", "error");
                });
            },
            refresh() {
                $('#tableList').bootstrapTable(('refresh'));
            },
        }
    });
};

//表单验证
function validateForm() {
    //validate方法参数可选
    return $("#myform").validate({
        rules: {
            enterpriseName: {
                required: true,//必填
                minlength: 1, //最少1个字符
            },
            userName: {
                required: true,//必填
                minlength: 1, //最少1个字符
            },
            idcard: {
                required: true,//必填
                minlength: 1, //最少1个字符
            },
            // harmlessId: {
            //     required: true,//必填
            //     minlength: 1, //最少1个字符
            // },
            // harmlessId2: {
            //     required: true,//必填
            //     minlength: 1, //最少1个字符
            // },
        },
        //错误信息提示
        messages: {
            enterpriseName: {
                required: "(必填)",
                minlength: "最少1位",
            },
            userName: {
                required: "(必填)",
                minlength: "最少1位",
            },
            idcard: {
                required: "(必填)",
                minlength: "最少1位",
            },
            // harmlessId: {
            //     required: "(必填)",
            //     minlength: "最少1位",
            // },
            // harmlessId2: {
            //     required: "(必填)",
            //     minlength: "最少1位",
            // },
        },
    }).form();
}
function getHarmlessId() {
    $.ajax({
        type: "get",
        url: "/harmlessenterprise/getHarmlessId",
        dataType : "json",
        contentType: "application/json",
        success: function (data, status) {
            //清空
            $("#harmlessId").empty();
            //将无害化赋值给下拉列表
            $.each(data,function (index,value) {
                $("#harmlessId").append("<option value='"+value.enterpriseId+"'>"+value.enterpriseName+"</option>");
            })
        }
    });
}
function getHarmlessId2() {
    $.ajax({
        type: "get",
        url: "/harmlessenterprise/getHarmlessId",
        dataType : "json",
        contentType: "application/json",
        success: function (data, status) {
            //清空
            $("#harmlessId2").empty();
            //将无害化赋值给下拉列表
            $.each(data,function (index,value) {
                $("#harmlessId2").append("<option value='"+value.enterpriseId+"'>"+value.enterpriseName+"</option>");
            })
        }
    });
}
